// 封装 http
const http = {
  baseUrl: 'http://127.0.0.1:3000',
  request(config) {
    config = beforeRequest(config);
    config.url = this.baseUrl + config.url;
    return new Promise((resolve, reject) => {
      uni.request(config).then(res => {
        let [err, resp] = res;
        const response = beforeResponse(resp);
        resolve(response)
      })
      .catch(err => {
        errorHandle()
        reject(err)
      })
    })
  },
  get (url, data, auth) {
    return this.request({
      url: url,
      data: data,
      method: "GET",
      auth: auth,
    })
  },
  delete(url, auth) {
    return this.request({
      url: url,
      method: "DELETE",
      auth: auth,
    })
  },
  post (url, data, auth){
    console.log(this);
    return this.request({
      url: url,
      data: data,
      method: "POST",
      auth: auth,
    })
  }
}

const beforeRequest = (config) => {
  console.log('请求拦截器', config);
  config['header'] = {};
  
  if (config?.auth) {
    // 在请求头中添加token
    if (uni.getStorageSync('token')) {
      config.header['Authorization'] = 'Bearer ' + uni.getStorageSync('token');
    } else {
      // 没有登录，无访问权限，重定向
      uni.navigateTo({
        url: '/pages/user/login'
      })
    }
    
  }
  
  return config
}

const beforeResponse = (response) => {
  console.log('相应拦截器', response)
  let statusCode = response.statusCode.toString()
  if (['200', '201','204'].indexOf('statusCode') < 0) {
    if (response.data.error) {
      uni.showToast({
        title: response.data.error.toString(),
        duration: 1000,
        icon: 'none',
      })
    }
  }
  return response
}

const errorHandle = (err) => {
  console.log("网络异常", err);
}

function httpTest() {
  let url = baseUrl + '/api/users/login';
  uni.request({
      url: url, //仅为示例，并非真实接口地址。
      data: {
          username: 'abc',
          password: 'admin133'
      },
      header: {
          'custom-header': 'hello' //自定义请求头信息
      },
      success: (res) => {
          console.log("res");
      }
  });
}

export default http;



